package com.solve.auth.Service.Impl;

import com.solve.auth.dao.PermissionMapper;
import com.solve.auth.dao.RoleMapper;
import com.solve.auth.dao.UserMapper;
import com.solve.auth.entity.ManagerInfo;
import com.solve.auth.entity.SysRole;
import com.solve.auth.entity.User;
import com.solve.auth.entity.UserExample;
import com.solve.auth.shiro.JWTToken;
import com.solve.auth.shiro.ShiroKit;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private PermissionMapper permissionMapper;


    public ManagerInfo findByUsername(String username) {
        ManagerInfo managerInfo = userMapper.selectByNameGetManager(username);
        User user = new User();
        user.setUuid(managerInfo.getUuid());
        List<SysRole> sysRoles = roleMapper.selectRoleByUser(user);
        managerInfo.setRoles(sysRoles);
        return managerInfo;
    }

    public void saveUserInfo(User user) throws Exception{
        //首先检查当前用户名是否存在

        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserNameEqualTo(user.getUserName());
        int count = userMapper.countByExample(userExample);
        if (count != 0){//
            throw new Exception("当前用户名已存在");
        }

        user.setSalt(String.valueOf(((int)(Math.random()*10000))));
        String encodedPassword = ShiroKit.md5(user.getPassword(),user.getUserName()+user.getSalt());
        user.setPassword(encodedPassword);
        user.setUuid(UUID.randomUUID().toString());
        userMapper.insert(user);
    }

    public User getUserAllInfo(String userId){

        User user = userMapper.selectUserAllInfo(userId);
        return user;
    }

    public User getUserIntegral(String userId){
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }

    public User getUserByName(String name) {
        User user =  userMapper.selectByName(name);
        if (user == null) {
            return null;
        }
        return user;
    }
}
